package com.sys.sysserver.controller;

import com.sys.sysserver.domain.constant.JwtClaimsConstant;
import com.sys.sysserver.domain.dto.UserLoginDTO;
import com.sys.sysserver.domain.po.User;
import com.sys.sysserver.domain.properties.JwtProperties;
import com.sys.sysserver.domain.vo.UserLoginVO;
import com.sys.sysserver.service.LoginService;
import com.sys.sysserver.utils.JwtUtil;
import com.sys.sysserver.utils.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class LoginController {
    private final LoginService userService;
    private final JwtProperties jwtProperties;

    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO) throws Exception {
        log.info("\n\n正在执行登录操作:=>{}\n\n", userLoginDTO);
        User user = userService.login(userLoginDTO);

        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());

        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .password(user.getPassword())
                .token(token)
                .build();


        return Result.success(userLoginVO);
    }
}
